package com.example.demo.service;


import com.example.demo.exception.BusinessException;
import com.example.demo.model.Course;
import com.example.demo.model.CourseMaterial;
import com.example.demo.model.CourseSection;
import com.example.demo.repository.CourseRepository;
import lombok.RequiredArgsConstructor;
import org.modelmapper.ModelMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class CourseUploadService {
    private final CourseRepository courseRepository;
    private final CourseSectionRepository sectionRepository;
    private final CourseMaterialRepository materialRepository;
    private final FileStorageService fileStorageService;
    private final ModelMapper modelMapper;

    @Transactional
    public CourseSection uploadCourseMaterials(CourseUpload  upload , Long teacherId) {
        // 验证课程是否存在且属于该教师
        Course course = courseRepository.findByIdAndTeacherId(upload .getCourseId(), teacherId)
                .orElseThrow(() -> new BusinessException("课程不存在或您没有权限"));

        // 创建课程章节
        CourseSection section = new CourseSection();
        section.setCourse(course);
        section.setTitle(upload.getSectionTitle());
        section.setDescription(upload.getSectionDescription());

        // 设置章节顺序（当前课程最后一个章节的sequence+1）
        Integer maxSequence = sectionRepository.findMaxSequenceByCourseId(course.getId());
        section.setSequence(maxSequence != null ? maxSequence + 1 : 1);

        section = sectionRepository.save(section);

        // 处理上传的文件
        for (int i = 0; i < upload .getFiles().size(); i++) {
            MultipartFile file = upload .getFiles().get(i);
            String fileUrl = fileStorageService.storeFile(file);

            CourseMaterial material = new CourseMaterial();
            material.setSection(section);
            material.setTitle(file.getOriginalFilename());
            material.setFileUrl(fileUrl);
            material.setFileSize(file.getSize());
            material.setFileType(file.getContentType());
            material.setSequence(i + 1);

            materialRepository.save(material);
        }

        return convertTo (section);
    }

    @Transactional(readOnly = true)
    public List<CourseSection > getCourseSections(Long courseId, Long teacherId) {
        // 验证教师是否有权限访问该课程
        if (!courseRepository.existsByIdAndTeacherId(courseId, teacherId)) {
            throw new BusinessException("您没有权限查看此课程内容");
        }

        return sectionRepository.findByCourseIdOrderBySequenceAsc(courseId).stream()
                .map(this::convertTo )
                .collect(Collectors.toList());
    }

    @Transactional
    public void deleteSection(Long sectionId, Long teacherId) {
        CourseSection section = sectionRepository.findById(sectionId)
                .orElseThrow(() -> new ResourceNotFoundException("章节不存在"));

        // 验证教师权限
        if (!section.getCourse().getTeacher().getId().equals(teacherId)) {
            throw new BusinessException("您没有权限删除此章节");
        }

        // 删除关联的资料文件
        section.getMaterials().forEach(material -> {
            fileStorageService.deleteFile(material.getFileUrl());
        });

        sectionRepository.delete(section);
    }

    private CourseSection  convertTo (CourseSection section) {
        CourseSection    c= modelMapper.map(section, CourseSection .class);
         c.setCourseId(section.getCourse().getId());

        // 转换资料列表并按顺序排序
        if (section.getMaterials() != null) {
             c.setMaterials(section.getMaterials().stream()
                    .sorted(Comparator.comparingInt(CourseMaterial::getSequence))
                    .map(this::convertMaterialTo )
                    .collect(Collectors.toList()));
        }

        return c ;
    }

    private CourseMaterial  convertMaterialTo (CourseMaterial material) {
        CourseMaterial  c  = modelMapper.map(material, CourseMaterial .class);
         c.setSectionId(material.getSection().getId());
        return  c;
    }
}